<template>
  <div>

    <el-image v-for='item in data.urls' @click='methods.addImg(item)' style="width: 50px; height: 40px;margin-right: 10px" :src="item" fit="contain" />

    <div style="width: 100%;height: 90vh; overflow: hidden;border: 1px solid #ccc">
      <div ref='map' id="map" :style="{ width: '100%',height: '100%'}"></div>
    </div>

    <el-dialog title="编辑" v-model="data.dialogVisible" width="500px" :before-close="methods.handleClose">
      <el-form ref="form" :model="data.form" label-width="120px">
        <el-form-item label="图标大小-宽度">
          <el-input v-model="data.form.iconWidth"></el-input>
        </el-form-item>
        <el-form-item label="图标大小-高度">
          <el-input v-model="data.form.iconHeight"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="methods.delete">删除标记</el-button>
        <el-button type="primary" @click="methods.save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive } from 'vue'
  import mapboxgl from "mapbox-gl/dist/mapbox-gl.js";
  import "mapbox-gl/dist/mapbox-gl.css";
  import { MxMapBox } from "./js/index";

  let data = reactive({
    mapInst:null,
    showInfoWindow: false,
    popupTemp: null,
    lengeData: {
      lev1_show: true,
      lev2_show: true,
    },
    visible: false,
    mapDataCopy: [
      {
        iconWidth: 20,
        iconHeight: 20,
        iconUrl: "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
        latitude: 39.907485177029486,
        longitude: 116.38630928239297,
        copyIndex: 1
      },
      {
        iconWidth: "40",
        iconHeight: "40",
        iconUrl: "https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg",
        latitude: 39.90523863535458,
        longitude: 116.38750004796259,
        copyIndex: 2
      },
      {
        iconWidth: "40",
        iconHeight: "40",
        iconUrl: "https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg",
        latitude: 39.906538840615156,
        longitude: 116.39163018079654,
        copyIndex: 3
      },
      {
        iconWidth: "40",
        iconHeight: "40",
        iconUrl: "https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg",
        latitude: 39.9046625871614,
        longitude: 116.39216656168412,
        copyIndex: 4
      }
    ],
    param:{
      mapOrigin:[116.391305, 39.90553],
      ptCADOrigin:[578534.364205,411688.892661],
      meterInCADUnits:0.001,
      cadFile:'/demo/buf/mapcad.dwg',
    },
    dialogVisible:false,
    urls:[
      'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
      'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
      'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
      'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
      'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
      'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
      'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',
    ],
    form:{
      iconWidth:20,
      iconHeight:20,
      iconUrl:'',
    },
    copyIndex:null,
  });

  let map = MxMapBox.getMap();

  async function init(){

    mapboxgl.accessToken = ' ';
    MxMapBox.init({
      mapOrigin: data.param.mapOrigin,
      cadOrigin: data.param.ptCADOrigin,
      meterInCADUnits: data.param.meterInCADUnits,
      cadFile: data.param.cadFile,
      call: async (_map, _mxMap) => {
        methods.loadPoint(_map);
        data.mapInst = _map;
        data.mapInst.on('click', function (e) {
          const ids = e.originalEvent.target.id;
          data.copyIndex = null;
          if(ids){
            const index = ids.substring(15,ids.length);
            data.copyIndex = index;
            let row = data.mapDataCopy.find(item =>item.copyIndex == index);
            data.form = JSON.parse(JSON.stringify(row));
            data.dialogVisible = true;
          }else {
            if(data.form.iconUrl){
              let obj = {
                iconWidth:data.form.iconWidth,
                iconHeight:data.form.iconHeight,
                iconUrl:data.form.iconUrl,
                latitude:e.lngLat.lat,
                longitude:e.lngLat.lng,
                copyIndex:data.mapDataCopy.length + 1,
              }
              data.mapDataCopy.push(obj);
              window.localStorage.setItem('mapDataCopy', JSON.stringify(data.mapDataCopy));
              methods.addProp(data.mapInst,obj)
            }
          }
        });
      },
    });
  };

  let methods = {

    delete(){
      let index = data.mapDataCopy.findIndex(item =>item.copyIndex == data.copyIndex)
      data.mapDataCopy.splice(index,1);
      window.localStorage.setItem('mapDataCopy', JSON.stringify(data.mapDataCopy));
      const removeBtn = document.getElementById('markerId ' + 'marker' + data.copyIndex);
      removeBtn.remove();
      data.dialogVisible = false;
      data.form.iconUrl = '';
    },

    save(){
      data.dialogVisible = false;
      if(data.copyIndex){
        let index = data.mapDataCopy.findIndex(item =>item.copyIndex == data.copyIndex)
        data.mapDataCopy[index].iconWidth = data.form.iconWidth;
        data.mapDataCopy[index].iconHeight = data.form.iconHeight;
        window.localStorage.setItem('mapDataCopy', JSON.stringify(data.mapDataCopy));
        methods.addProp(data.mapInst,data.mapDataCopy[index]);
      }
    },

    // 加载点位
    loadPoint(map) {
      data.mapDataCopy.forEach((item) => {
        methods.addProp(map,item)
      })
    },

    //添加弹框
    addProp(map,item){
      let coordinate = [Number(item.longitude), Number(item.latitude)]
      let el = document.createElement('div')
      el.id = 'markerId ' + 'marker' + item.copyIndex;
      el.style.width = item.iconWidth + 'px';
      el.style.height = item.iconHeight + 'px';
      el.style.background = `url("${item.iconUrl}") no-repeat`;
      el.style.backgroundSize = '100% 100%';
      new mapboxgl.Marker({draggable: true, element: el}).setLngLat(coordinate).setOffset([0, -19]).addTo(map) // 将标记添加到地图上

      /*if(type === 1){

        // 添加弹窗
        let popup = new mapboxgl.Popup({ offset: 25 }).setHTML(`<div class="makerTop">
                        <h2 class="markerHear" > 综合办一处 ${item.copyIndex}</h2>
                    </div>
                    <div class="markerBody" >
                       <p>设在单位：兴安盟乌兰浩特市市政府</p>
                       <p>详细地址：兴安盟乌兰浩特市</p>
                       <p>负责人：杨子林</p>
                       <p>军电：0311-2564558</p>
                    </div>`);
        new mapboxgl.Marker(el)
            .setLngLat(coordinate)
            .setPopup(popup) // sets a popup on this marker
            .addTo(map)

      }*/

    },


    handleClose(){
      data.dialogVisible = false;
      data.form.iconUrl = '';
    },


    addImg(item){
      data.form.iconUrl = item;
      data.dialogVisible = true;
    }

  };

  onMounted(()=>{
    if(window.localStorage.getItem('mapDataCopy')){
      data.mapDataCopy = JSON.parse(window.localStorage.getItem('mapDataCopy'));
    }
    init();
  })

</script>
<style>
  #map{
    width: 100%;
    height: 100%;
    background: #000;
  }

  .mapboxgl-popup-content{
    background: #1a77af;
    border-radius: 3px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
    color: #ffffff;
    width: 200px;
  }
  #markerId{
    width: 30px;
    height: 30px;
    background: url("../assets/image/mapIcon.png") no-repeat;
    background-size: 100% 100%;
  }
</style>
